package info.batcloud.fanli.admin.controller;

import info.batcloud.fanli.admin.permission.ManagerPermissions;
import info.batcloud.fanli.admin.permission.annotation.Permission;
import info.batcloud.fanli.core.domain.Result;
import info.batcloud.fanli.core.service.CommissionOrderService;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/api/commission-order")
@Permission(ManagerPermissions.COMMISSION_ORDER_MANAGE)
public class CommissionOrderController {

    @Inject
    private CommissionOrderService commissionOrderService;

    @PostMapping("/settle")
    public Object settle() {
        commissionOrderService.settle();
        return 1;
    }

    @PostMapping("/allocate/{id}")
    public Object allocate(@PathVariable long id, @RequestParam long userId) {
        Result result = commissionOrderService.allocateCommissionOrderToUser(userId, id);
        return result;
    }

    @GetMapping("/search")
    public Object search(CommissionOrderService.SearchParam param) {
        return commissionOrderService.search(param);
    }

    @GetMapping("/export")
    public Object export(CommissionOrderService.ExportParam param, HttpServletResponse response) throws IOException {
        File file = commissionOrderService.exportCommissionOrder(param);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = URLEncoder.encode("佣金订单", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + System.currentTimeMillis() + ".xls");
        try (InputStream is = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            file.delete();
        }
        return null;
    }
}
